package com.stylefeng.guns.modular.prediction.service.impl;

import com.stylefeng.guns.common.persistence.model.RiskFactor;
import com.stylefeng.guns.core.support.CollectionKit;
import com.stylefeng.guns.modular.prediction.service.IRiskFactorService;
import com.stylefeng.guns.modular.prediction.transfer.FishBoneDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FishBoneService {

	@Autowired
	private IRiskFactorService riskFactorService;

	public FishBoneDto fishBone() {
		RiskFactor rFroot = getRoot();
		if (rFroot == null) {
			return null;
		}
		FishBoneDto root =  toFishBone(rFroot,"Bold",18);
		setChildren(root);
		return root;
	}

	private void setChildren(FishBoneDto dto){
		List<FishBoneDto> children =
				riskFactorService.findByPid(dto.getId())
				                 .stream()
				                 .map(this::toFishBone)
				                 .collect(Collectors.toList());
		if (CollectionKit.isEmpty(children)) {
			return;
		}

		children.stream().forEach(this::setChildren);

		dto.setWeight("Bold");
		dto.setCauses(children);

	}

	private FishBoneDto toFishBone(RiskFactor riskFactor,String weight,Integer size) {
		FishBoneDto fishBoneDto = new FishBoneDto();
		fishBoneDto.setId(riskFactor.getId());
		fishBoneDto.setText(riskFactor.getName());
		fishBoneDto.setWeight(weight);
		fishBoneDto.setSize(size);
		return fishBoneDto;
	}

	private FishBoneDto toFishBone(RiskFactor riskFactor) {
		return toFishBone(riskFactor, null,null);
	}

	private FishBoneDto toFishBoneWithBold(RiskFactor riskFactor) {
		return toFishBone(riskFactor, "Bold", null);
	}


	private RiskFactor getRoot(){
		List<RiskFactor> rootList = riskFactorService.findByPid(0);
		if (rootList.size() == 0) {
			return null;
		}
		for (RiskFactor root : rootList) {
			if (root.getStatus() == 1) {
				return root;
			}
		}
		return rootList.get(0);
	}
}
